package com.ruicar.afs.cloud.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.admin.entity.SysRole;
import com.ruicar.afs.cloud.admin.entity.SysRoleDataScope;
import com.ruicar.afs.cloud.admin.entity.SysUserRole;
import com.ruicar.afs.cloud.admin.mapper.SysRoleMapper;
import com.ruicar.afs.cloud.admin.service.SysRoleDataScopeService;
import com.ruicar.afs.cloud.admin.service.SysRoleService;
import com.ruicar.afs.cloud.admin.service.SysUserRoleService;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.security.vo.RoleVo;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Fzero
 * @since 2017-10-29
 */
@Service
@AllArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
	private final SysUserRoleService userRoleService;
	private final SysRoleDataScopeService sysRoleDataScopeService;
	/**
	 * 通过用户ID，查询角色信息
	 *
	 * @param userId
	 * @return
	 */
	@Override
	public List findRolesByUserId(Long userId) {
		return baseMapper.listRolesByUserId(userId);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteByRoleIds(List<Long> ids) {
		for (Long id : ids) {
			List<SysUserRole> list = userRoleService.list(Wrappers.<SysUserRole>query().lambda().eq(SysUserRole::getRoleId, id));
			if (list != null && list.size() > 0) {
				throw  new AfsBaseException(CommonConstants.FAIL,"删除失败，包含正被用户使用关联的角色");
			}
		}
		this.remove(Wrappers.<SysRole>lambdaUpdate().in(SysRole::getId,ids));
		ids.forEach(id->{
			sysRoleDataScopeService.remove(Wrappers.<SysRoleDataScope>lambdaUpdate().eq(SysRoleDataScope::getRoleId,id));
		});
	}
}
